//
//  CZPictureSeletedView.swift
//  weibo27
//
//  Created by mac on 16/4/22.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

let PictureBrowerCellId = "PictureBrowerCellId"

class CZPictureBrowerView: UIViewController {
 
    private var urls:[NSURL]
    
    private var currentIndexPath: NSIndexPath
    
    init(urls:[NSURL],currentIndexPath:NSIndexPath){
        
        self.urls = urls
        
        self.currentIndexPath = currentIndexPath
        
        super.init(nibName: nil, bundle: nil)
        
        
    }
    
    //按钮的监听方法
    @objc private func closeClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func saveClick(){
//        print("点击了保存保存按钮")
        
        // 1 获取图片
        let cell = collectionView.visibleCells()[0] as! CZPictureBrowerCell
        
        guard let image = cell.imageView.image else{
            return
        }
        
        // 2 保存图片
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo: AnyObject?){
    
        let message = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)
    }
    
//    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func loadView() {
        
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.width += 20
        view = UIView(frame: rect)
        
        setupUI()
    }
    
    override func viewDidLoad() {
        
//        print(self.urls)
        
//        print(self.currentIndexPath)

        self.navigationController?.navigationBar.tintColor = UIColor.blackColor()
        
        //点击后跳到指定的位置
        collectionView.scrollToItemAtIndexPath(currentIndexPath, atScrollPosition: .CenteredHorizontally, animated: true)
    }
    
    
    //懒加载控件
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PictureBrowerFlowLayout())
    private lazy var saveBtn:UIButton = {
    
        let button = UIButton()
        button.backgroundColor = UIColor.darkGrayColor()
        button.setTitle("保存", forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        return button
    }()
    
    private lazy var closeBtn:UIButton = {
        
        let button = UIButton()
        button.backgroundColor = UIColor.darkGrayColor()
        button.setTitle("取消", forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        return button
    }()
    
    private class PictureBrowerFlowLayout:UICollectionViewFlowLayout{
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            itemSize = (collectionView?.bounds.size)!

            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            
//            collectionView?.showsHorizontalScrollIndicator = false
            
            
        }
    }
}


// MARK: 设置UI
private extension CZPictureBrowerView{
    
    // 1 添加
    private func setupUI(){
       
        view.addSubview(collectionView)
        view.addSubview(saveBtn)
        view.addSubview(closeBtn)
        
        // 2 设置frame
        
        collectionView.frame = view.bounds
        
        saveBtn.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(-8)
            make.right.equalTo(-8)
            make.size.equalTo(CGSize(width: 100, height: 30))
        }
        
        closeBtn.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(-8)
            make.left.equalTo(8)
            make.size.equalTo(CGSize(width: 100, height: 30))
        }
        
        //3 添加监听方法
        saveBtn.addTarget(self, action: "saveClick", forControlEvents: .TouchUpInside)
        closeBtn.addTarget(self, action: "closeClick", forControlEvents: .TouchUpInside)
        
        //4 准备控件
        prepareForCollectionView()
    }
    //准备collectionView
    private func prepareForCollectionView(){
        
        collectionView.registerClass(CZPictureBrowerCell.self, forCellWithReuseIdentifier: PictureBrowerCellId)
        
        collectionView.dataSource = self
    
    }
    
}

// MARK:数据源方法
extension CZPictureBrowerView: UICollectionViewDataSource{
    
     func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        
        return urls.count ?? 0
    }
    
     func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureBrowerCellId, forIndexPath: indexPath) as! CZPictureBrowerCell
        
        cell.backgroundColor = UIColor.whiteColor()
        
        cell.imageUrl = urls[indexPath.row]
        
        //设置代理
        cell.pictureBrowerCellDelegate = self
        
        return cell
    }
}

// MARK: 遵循cell的代理
extension CZPictureBrowerView:PictureBrowerCellDelegate{
    
    func pictureBrowerCellDidTapImage(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}























